<template>
    <LayoutWrap class="loglist">
        <el-form @submit.native.prevent ref="formSearch" :inline="true" :model="formSearch" label-width="90px">
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="关键词" prop="keyName">
                        <el-select
                            class="custom-the-select_key"
                            popper-class="custom-the-select-popper_key"
                            v-model="formSearch.keyName"
                            placeholder="请选择"
                            style="width: 105px;margin-right: 10px;"
                        >
                            <el-option
                                v-for="item in keyOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                            >
                            </el-option>
                        </el-select>
                        <br v-if="isMobile" />
                        <el-input
                            v-model="formSearch.keyValue"
                            placeholder="请输入关键字检索"
                            @keyup.enter.native="getList"
                            style="width: 206px"
                            clearable
                        ></el-input>
                    </el-form-item>
                </div>
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="操作人" prop="operator">
                        <el-input
                            v-model="formSearch.operator"
                            placeholder="请输入关键字检索"
                            @keyup.enter.native="getList"
                            style="width: 322px"
                            clearable
                        ></el-input>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="操作时间" prop="startDate">
                        <el-date-picker
                            type="date"
                            placeholder="选择日期"
                            format="yyyy/MM/dd"
                            value-format="yyyy-MM-dd"
                            prefix-icon="false"
                            v-model="formSearch.startDate"
                            :clearable="true"
                            class="custom-the-datepicker"
                            style="width: 88px;margin-right: 5px;"
                            @change="onChangeDate($event, 'startDate')"
                        ></el-date-picker>
                        <el-time-select
                            prefix-icon="false"
                            placeholder="起始时间"
                            v-model="formSearch.startTime"
                            class="custom-the-datepicker"
                            style="width: 60px;"
                            :clearable="false"
                            :picker-options="{
                                start: '00:00',
                                step: '01:00',
                                end: '24:00'
                            }"
                            @change="onChangeDate($event, 'startTime')"
                        >
                        </el-time-select>
                        <span style="display: inline-block; padding: 0 5px;">-</span>
                        <el-date-picker
                            type="date"
                            placeholder="选择日期"
                            format="yyyy/MM/dd"
                            value-format="yyyy-MM-dd"
                            prefix-icon="false"
                            v-model="formSearch.endDate"
                            :clearable="true"
                            class="custom-the-datepicker"
                            style="width: 88px;margin-right: 5px;"
                            @change="onChangeDate($event, 'endDate')"
                        ></el-date-picker>
                        <el-time-select
                            prefix-icon="false"
                            placeholder="结束时间"
                            v-model="formSearch.endTime"
                            class="custom-the-datepicker"
                            style="width: 60px; margin-right: 5px;"
                            :clearable="false"
                            :picker-options="{
                                start: '00:00',
                                step: '01:00',
                                end: '24:00'
                            }"
                            @change="onChangeDate($event, 'endTime')"
                        >
                        </el-time-select>
                    </el-form-item>
                </div>
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="时间快捷项" prop="selectMenu">
                        <el-select
                            style="width: 322px"
                            v-model="formSearch.selectMenu"
                            placeholder="请选择"
                            :popper-append-to-body="false"
                            clearable
                            @change="onChangeTimeRange"
                            @clear="onChangeTimeRange('All')"
                        >
                            <el-option
                                v-for="item in menuOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>

            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="  ">
                        <el-button type="primary" style="min-width: 120px;" @click="getList">查询</el-button>
                        <br v-if="isMobile" />
                        <el-button type="default" style="min-width: 120px;" @click="resetForm('formSearch')"
                            >重置</el-button
                        >
                    </el-form-item>
                </div>
            </div>
        </el-form>
        <ul class="list-head" v-if="isOperation">
            <li class="list-head-item">
                <el-button
                    style="min-width:80px;"
                    :disabled="!isMultSelect"
                    @click="multipleDeleteVisible = true"
                    type="danger"
                    >批量删除</el-button
                >
            </li>
        </ul>

        <el-table
            v-loading="isLoading"
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
            ref="multipleUpdateTable"
        >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column type="index" :index="indexMethod"> </el-table-column>
            <el-table-column prop="operatorDate" label="操作时间">
                <template v-slot="{row}">
                    {{ row.operatorDate | formatDateFillStr }}
                </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人">
                <template v-slot="{row}">{{ row.operator && row.operator.name }}</template>
            </el-table-column>
            <el-table-column prop="name" label="模块名称"> </el-table-column>
            <el-table-column prop="remark" label="备注"> </el-table-column>
            <el-table-column prop="subject" label="摘要">
                <template v-slot="{row}">
                    <el-button @click="onClickDrawer('摘要', row.subject)" type="text" class="esptext-wrapper">
                        <div class="esptext-item">{{ row.subject }}</div>
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="body" label="内容">
                <template v-slot="{row}">
                    <el-button @click="onClickDrawer('内容', JSON.parse(row.body))" type="text" class="esptext-wrapper">
                        <div class="esptext-item">{{ row.body }}</div>
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="ip" label="操作IP"> </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            @change="onChangePage"
        />
        <el-drawer :title="drawerTitle" :visible.sync="drawerVisible" direction="rtl">
            <div style="padding:0 20px;white-space: pre-line;">
                <JsonEditor v-model="drawerContext"> </JsonEditor>
            </div>
        </el-drawer>
        <TheElDialog
            title="批量删除"
            :visible.sync="multipleDeleteVisible"
            minWidth
            @closed="handleSelectionChange(multipleValueSelection)"
        >
            <span>你确定删除下面日志吗？</span>
            <el-table v-loading="isMultipleLoading" :data="multipleSelection" :border="false" style="width: 100%">
                <el-table-column prop="operatorDate" label="操作时间">
                    <template v-slot="{row}">
                        {{ row.operatorDate | formatDateFillStr }}
                    </template>
                </el-table-column>
                <el-table-column prop="operator" label="操作人">
                    <template v-slot="{row}">{{ row.operator && row.operator.name }}</template>
                </el-table-column>
                <el-table-column prop="name" label="模块名称"> </el-table-column>
                <el-table-column prop="remark" label="备注" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="subject" label="摘要" show-overflow-tooltip :width="200">
                    <!-- <template v-slot="{row}">
                        <span>{{ row.subject }}</span>
                    </template> -->
                </el-table-column>
                <el-table-column prop="ip" label="操作IP"> </el-table-column>
                <el-table-column align="center" label="操作" :width="50">
                    <template v-slot="{row}">
                        <el-button size="small" @click="onRemoveUpdateSelection(row)" type="text">
                            移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="isMultipleLoading" @click="multipleDeleteVisible = false">取 消</el-button>
                <el-button
                    :loading="isMultipleLoading"
                    type="primary"
                    @click="onClickMultipleOkDelete(multipleSelection)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
    </LayoutWrap>
</template>
<script>
import {mapGetters} from 'vuex';
import {getLogList, deleteLogByIds} from '@/api/loglist';
import {THE_MOMENT_YYYYMMDD_HHMMSS} from '@/utils/constant';
import {deepCopy} from '@/utils/utils';
import {v4 as uuidv4} from 'uuid';
import moment from 'moment';
import JsonEditor from '@/components/JsonEditor';
import {mixinIsOperation} from '@/mixins';

export default {
    name: 'loglist',
    components: {JsonEditor},
    mixins: [mixinIsOperation],
    data() {
        return {
            menuOptions: [
                // {label: '所有时间', value: 'All'},
                // {label: '自定义时间', value: 'CustomTime'},
                // {label: '今天', value: 'Today'},
                // {label: '最近一周', value: 'LastWeek'},
                // {label: '最近一个月', value: 'LastMonth'},
                // {label: '最近三个月', value: 'LastThreeMonths'}
            ],
            THE_MOMENT_YYYYMMDD_HHMMSS,
            formSearch: {
                startDate: '',
                startTime: '',
                endDate: '',
                endTime: '',

                selectMenu: 'All', // 'CustomTime' 'LastWeek',

                operator: '',

                keyName: 'name',
                keyValue: '',
                pageSize: 10,
                page: 1,
                count: 0
            },
            keyOptions: [
                {label: '模块名称', value: 'name', disabled: false},
                {label: '备注', value: 'remark', disabled: false},
                {label: '摘要', value: 'subject', disabled: false},
                // {label: '内容', value: 'body', disabled: false},
                {label: 'IP地址', value: 'ip', disabled: false}
                // operatorDate
                // operatorDate
                // operator
            ],
            tableData: [],
            isLoading: false,
            visibleDetail: false,
            title: '添加',
            dialogVisible: false,
            dialogLoading: false,
            multipleSelection: [],
            multipleValueSelection: [],
            multipleDeleteVisible: false, // 批量删除打开、关闭
            isMultipleLoading: false,
            drawerTitle: '',
            drawerContext: '',
            drawerVisible: false
        };
    },
    computed: {
        ...mapGetters({
            isMobile: 'app/isMobile'
        }),
        isMultSelect() {
            return this.multipleSelection.length > 0;
        }
    },
    created() {
        this.getList();

        this.menuOptions = [
            {
                label: '所有时间',
                value: 'All',
                method: () => {
                    this.formSearch = {
                        ...this.formSearch,
                        startDate: '',
                        startTime: '',
                        endDate: '',
                        endTime: ''
                    };
                }
            },
            {label: '自定义时间', value: 'CustomTime', method: () => {}},
            {
                label: '今天',
                value: 'Today',
                method: () => {
                    const startDate = moment().format('YYYY-MM-DD');
                    const endDate = startDate;

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            },
            {
                label: '最近一周',
                value: 'LastWeek',
                method: () => {
                    const startDate = moment()
                        .add(-7, 'days')
                        .format('YYYY-MM-DD');
                    const endDate = moment().format('YYYY-MM-DD');

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            },
            {
                label: '最近一个月',
                value: 'LastMonth',
                method: () => {
                    const startDate = moment()
                        .add(-1, 'months')
                        .format('YYYY-MM-DD');
                    const endDate = moment().format('YYYY-MM-DD');

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            },
            {
                label: '最近三个月',
                value: 'LastThreeMonths',
                method: () => {
                    const startDate = moment()
                        .add(-3, 'months')
                        .format('YYYY-MM-DD');
                    const endDate = moment().format('YYYY-MM-DD');

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            }
        ];
    },
    methods: {
        onClickDrawer(title, context) {
            this.drawerVisible = true;
            this.drawerTitle = title;
            this.drawerContext = typeof context === 'string' ? context.split(',') : context;
        },
        onChangeDate(value, type) {
            this.formSearch.selectMenu = 'CustomTime';

            if (type === 'startDate' && !value) {
                this.formSearch = {...this.formSearch, startTime: ''};
            }
            if (type === 'startDate' && value && !this.formSearch.startTime) {
                this.formSearch = {...this.formSearch, startTime: '00:00'};
            }
            if (type === 'endDate' && !value) {
                this.formSearch = {...this.formSearch, endTime: ''};
            }
            if (type === 'endDate' && value && !this.formSearch.endTime) {
                this.formSearch = {...this.formSearch, endTime: '24:00'};
            }
        },
        onChangeTimeRange(value) {
            const target = this.menuOptions.find(item => item.value === value);
            if (target && target.method) {
                target.method();
            }
        },
        indexMethod(index) {
            return index + 1 + (this.formSearch.page - 1) * this.formSearch.pageSize;
        },
        onRemoveUpdateSelection(row) {
            this.multipleSelection = this.multipleSelection.filter(({uuid}) => uuid !== row.uuid);
            this.multipleValueSelection = this.multipleValueSelection.filter(({uuid}) => uuid !== row.uuid);
            const tRow = this.tableData.find(item => row._id && item._id === row._id);
            tRow && this.$refs.multipleUpdateTable.toggleRowSelection(tRow, false);
        },
        onChangePage(value) {
            this.formSearch = {...this.formSearch, ...value};
            this.getList();
        },
        resetForm(formNmae) {
            const formSearch = this.$options.data().formSearch;

            this.formSearch = {
                ...this.formSearch,
                keyName: formSearch.keyName,
                keyValue: formSearch.keyValue,
                page: formSearch.page,
                pageSize: formSearch.pageSize,
                operator: formSearch.operator,
                selectMenu: formSearch.selectMenu,
                startDate: formSearch.startDate,
                startTime: formSearch.startTime,
                endDate: formSearch.endDate,
                endTime: formSearch.endTime
            };
        },
        handleSelectionChange(value) {
            this.multipleValueSelection = value;
            this.multipleSelection = deepCopy(value).map(item => {
                item.uuid = uuidv4();
                return item;
            });
        },
        // 批量删除
        onClickMultipleOkDelete(multipleSelection) {
            if (multipleSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量修改失败'});
                return;
            }
            this.isMultipleLoading = true;
            deleteLogByIds(multipleSelection.map(item => item._id))
                .then(res => {
                    this.getList();
                })
                .catch(error => {
                    const data = error.response && error.response.data;
                    if (data && data.error) {
                        this.$message({showClose: true, type: 'error', message: data.error});
                    } else {
                        this.$message({showClose: true, type: 'error', message: '批量删除失败'});
                    }
                    console.error(error);
                })
                .finally(() => {
                    this.isMultipleLoading = false;
                    this.multipleDeleteVisible = false;
                });
        },
        // 获取列表数据
        getList() {
            this.isLoading = true;
            const formSearch = this.formSearch;
            const newItem = {
                pageSize: formSearch.pageSize,
                page: formSearch.page,
                // select: 'operatorDate,operator,remark,name,subject,ip',
                sort: '-operatorDate',
                'operator.name': formSearch.operator || undefined
            };
            if (formSearch.startDate || formSearch.endDate) {
                newItem.operatorDate = {};

                if (formSearch.startDate) {
                    newItem.operatorDate.gte = new Date(`${formSearch.startDate} ${formSearch.startTime}`).getTime();
                }
                if (formSearch.endDate) {
                    newItem.operatorDate.lte = new Date(`${formSearch.endDate} ${formSearch.endTime}`).getTime();
                }
            }

            // console.log('newItem :>> ', JSON.stringify(newItem));

            if (formSearch.keyValue) {
                newItem[formSearch.keyName] = formSearch.keyValue;
            }
            getLogList(newItem)
                .then(({data: res}) => {
                    if (res.status === 200) {
                        const {data, count, page, pageSize} = res;
                        this.tableData = data;
                        this.formSearch = {...this.formSearch, page, pageSize, count};
                    }
                })
                .catch(error => {
                    const data = error.response && error.response.data;
                    if (data && data.error) {
                        this.$message({showClose: true, type: 'error', message: data.error});
                    }
                    console.log(error);
                })
                .finally(() => (this.isLoading = false));
        }
    }
};
</script>

<style lang="scss">
.el-tooltip__popper {
    max-width: 75%;
}
.esptext-wrapper {
    text-align: left;
    white-space: normal;
}
.esptext-item {
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    // cursor: pointer;
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
}
</style>

<style lang="scss" scoped>
.table-header {
    margin: 30px 0 20px 0;
}
.custom-the-datepicker,
.custom-the-select_time,
.custom-the-select_key {
    ::v-deep {
        .el-input__inner {
            padding-left: 10px;
            padding-right: 10px;
        }
    }
}
.custom-the-select_time {
    // width: 115px + 180px;
}
.custom-the-select_time.CustomTime {
    ::v-deep {
        .el-input__inner {
            // color: #fff;
        }
    }
}
.custom-the-select_time.CustomTime {
    // width: 35px;
}

.search-wrap {
    display: flex;
    flex-flow: row wrap;
    .search-item.left {
        min-width: 455px;
    }
}
</style>
